package com.tg.app.activity.device.add;

import static android.content.Context.MODE_PRIVATE;
import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.base.BaseFragment;
import com.bumptech.glide.Glide;
import com.tange.module.add.match.DeviceMatchQuery;
import com.tange.module.add.wifi.DeviceWiFiConfiguration;
import com.tg.app.R;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.ResourcesUtil;
import com.tange.base.toolkit.ScreenBrightUtils;
import com.tg.appcommon.android.SoundPlayerManager;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.http.entity.DeviceMatchBean;

public class QRCodeImageFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = "QRCodeImageFragment";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private static final String ARG_PARAM4 = "param4";
    private String random;
    private CheckBox mCheckBox;
    private OnAddDeviceListener listener;
    private String ssi;
    private String pwd;
    private String uuid;
    private String type;
    private String mUUID;
    private int screenBrightMode,screenBrightNum;

    private boolean playSound = true;

    private ImageView qrCodeImageView;

    private SoundPlayerManager soundPlayerManager;

    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    public QRCodeImageFragment() { }
    private boolean isAddSuccess = false;
    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }
    private final static int EVENT_ADD = 0;
    private int count = 0;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @SuppressLint("DefaultLocale")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == EVENT_ADD) {
                if (!isAddSuccess) {
                    if (count % 5 == 0) {
                        matching();
                    }

                    count++;
                    handler.sendEmptyMessageDelayed(EVENT_ADD, 1000);
                }
            } else if (msg.what == ApConnectActivityEx.EVENT_SET_NAME) {
                setDeviceName();
            }
        }
    };

    @Override
    public void onDetach() {
        TGLog.d("onDetach");
        super.onDetach();
        handler.removeMessages(EVENT_ADD);
        handler.removeCallbacksAndMessages(null);
    }

    public void setPlaySound(boolean playSound) {
        this.playSound = playSound;
    }

    private void matching() {
        TGLog.d("QRCodeImageFragment matching");
        if (!isAddSuccess) {

            DeviceMatchQuery.create().request(uuid, new DeviceMatchQuery.Callback() {
                @Override
                public void onSuccess(DeviceMatchBean content) {
                    if (!isAddSuccess) {
                        uuid = content.getUuid();
                        handler.removeMessages(ApConnectActivityEx.EVENT_SET_NAME);
                        handler.sendEmptyMessage(ApConnectActivityEx.EVENT_SET_NAME);
                        isAddSuccess = true;
                    }
                }

                @Override
                public void onError(int errorCode, String errorMsg) {

                }
            });
        }
    }

    private void setDeviceName() {
        handler.removeMessages(EVENT_ADD);
        handler.removeMessages(ApConnectActivityEx.EVENT_SET_NAME);
        Intent intent = new Intent(getContext(), ApSetNameActivity.class);
        intent.putExtra(ApiUrl.DEVICEID, 0);
        intent.putExtra(ApiUrl.DEVICE_TYPE, this.type);
        intent.putExtra(ApiUrl.DEVICE_UUID, mUUID);
        startActivity(intent);
    }

    public static QRCodeImageFragment newInstance(String param1, String param2, String uuid, String type) {
        QRCodeImageFragment fragment = new QRCodeImageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, uuid);
        args.putString(ARG_PARAM4, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        setToolbar();

        playSound();
    }


    private void playSound() {
        if (!playSound) {
            return;
        }
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
        if (getActivity() == null) {
            return;
        }
        soundPlayerManager = SoundPlayerManager.create(getActivity());
        uiHandler.postDelayed(() -> {
            if (getActivity() == null) return;
            if (soundPlayerManager != null) {
                soundPlayerManager.download(DeviceAddSoundConstants.WifiScan(getActivity()), true);
            }
        }, 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseSound();
    }

    private void pauseSound() {
        if (!playSound) {
            return;
        }
        uiHandler.removeCallbacksAndMessages(null);
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ssi = getArguments().getString(ARG_PARAM1);
            pwd = getArguments().getString(ARG_PARAM2);
            uuid = getArguments().getString(ARG_PARAM3);
            mUUID = uuid;
            type = getArguments().getString(ARG_PARAM4);
        }
        TGLog.d("ssi = " + ssi + ", pwd = " + pwd + ", uuid = " + uuid);
        setToolbar();
        handler.sendEmptyMessageDelayed(EVENT_ADD, 1000);
    }

    private void setToolbar() {
        Activity activity = getActivity();
        if (activity instanceof ScanQrcodeActivity) {
            ScanQrcodeActivity scanQrcodeActivity =  ((ScanQrcodeActivity)activity);
            scanQrcodeActivity.setToolbar(R.drawable.ic_back_btn, ResourcesUtil.getString(R.string.txt_scan_add_type));
            if (scanQrcodeActivity.getRightButton() != null) {
                scanQrcodeActivity.getRightButton().setVisibility(View.INVISIBLE);
            }
            if (scanQrcodeActivity.getBackButton() != null) {
                scanQrcodeActivity.getBackButton().setOnClickListener(v -> ActivityHelper.gotoDeviceListPage(getActivity()));
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_qrcode_image, container, false);
        mActivity = getActivity();
        initView(view);
        return view;
    }

    private void initView(View view) {
        qrCodeImageView = view.findViewById(R.id.qrcode_image_view);
        Button heraTipsButton = view.findViewById(R.id.hear_tips_button);
        heraTipsButton.setOnClickListener(this);
        ImageView imageView = view.findViewById(R.id.scan_image_view);
        Glide.with(mActivity).asGif().load(R.mipmap.scan).into(imageView);
        mCheckBox = view.findViewById(R.id.nothing_hear_text_view);
        view.findViewById(R.id.nothing_hear_text_view).setOnClickListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        generateQRCodeImage();
        turnBrightMax();
    }

    private void generateQRCodeImage() {
        String userId = String.valueOf(mActivity.getSharedPreferences(CommonConstants.PRE_SPNAME, MODE_PRIVATE).getInt(CommonConstants.PRE_USER_ID, -1));
        if (TextUtils.isEmpty(pwd)){
            pwd = "null";
        }
        random = DeviceWiFiConfiguration.createBindToken();
        String content = DeviceWiFiConfiguration.createWiFiConfig(ssi, pwd, userId, random);
        Bitmap bitmap = DeviceWiFiConfiguration.createQrCode(content, getScreenWidth() - 10, getScreenWidth() - 10);
        qrCodeImageView.setImageBitmap(bitmap);
    }

    private void turnBrightMax(){
        screenBrightMode = ScreenBrightUtils.getScreenMode(mActivity);
        screenBrightNum = ScreenBrightUtils.getScreenBrightness(mActivity);
        if (screenBrightMode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC){
            ScreenBrightUtils.setScreenMode(mActivity,SCREEN_BRIGHTNESS_MODE_MANUAL);
        }
        ScreenBrightUtils.setScreenBrightness(mActivity,255);
    }

    @Override

    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.hear_tips_button) {
            if (!mCheckBox.isChecked()){
                TGToast.showToast(R.string.txt_checkbox_tip);
                return;
            }

            ScreenBrightUtils.setScreenBrightness(mActivity, screenBrightMode);
            ScreenBrightUtils.setScreenBrightness(mActivity, screenBrightNum);

            if (TGGlobalConfigHelper.getInstance().isAddDeviceByScanAp()){
                if (listener != null) {
                    listener.onDeviceConnecting(random, AddFragmentTabActivity.TYPE_QR_CODE);
                }
            }else{
                ActivityHelper.goToConnectActivity(getActivity(), ssi, pwd, uuid, random, 0, "scan", playSound, null);
            }
        }
    }
}
